package com.hutiao.snowhb.actions.wechat;

import java.text.DecimalFormat;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.beans.factory.annotation.Autowired;

import com.hutiao.snowhb.common.MongoUtil;
import com.hutiao.snowhb.entities.SnowMM;
import com.hutiao.snowhb.entities.SnowMMLocation;
import com.hutiao.snowhb.entities.UserLocation;
import com.hutiao.snowhb.resource.ConfigInfo;
import com.hutiao.snowhb.service.SnowMMService;
import com.hutiao.snowhb.wechat.tools.WeiXinTools;
import com.hutiao.snowhb.wechat.vo.WxRecvGeoMsg;
import com.hutiao.snowhb.wechat.vo.WxRecvLinkMsg;
import com.hutiao.snowhb.wechat.vo.WxRecvVideoMsg;
import com.hutiao.snowhb.wechat.vo.WxRecvVoiceMsg;
import com.hutiao.snowhb.wechat.vo.WxSendMsg;
import com.hutiao.snowhb.wechat.vo.WxSendNewsMsg;
import com.hutiao.snowhb.wechat.vo.WxSendTextMsg;
import com.opensymphony.xwork2.ActionSupport;

@Namespace("/wechat")
public class HandleOtherMsgAction extends ActionSupport implements ServletRequestAware {

	private static final long serialVersionUID = -3485428114165386178L;

	private static Logger logger = Logger.getLogger(HandleOtherMsgAction.class);

	private HttpServletRequest request;

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	private String result;
	
	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}
	
	@Autowired
	private SnowMMService mmService;
	
	
	
	@Action(value="handlevoicemsg",
			results = {
				@Result(name="success",type="xmlstr", params={"stringName", "result"})})
	public String handleVoiceMsg() throws Exception {
		
		logger.info("msg type is WxRecvVoiceMsg");
		
		WxRecvVoiceMsg recvMsg = (WxRecvVoiceMsg) this.request.getAttribute("recvMsg");
		WxSendMsg sendMsg = WeiXinTools.builderSendByRecv(recvMsg);
		this.result = WeiXinTools.getSendXmlStr(sendMsg);
		
		return SUCCESS;
	}
	
	@Action(value="handlevideomsg",
			results = {
				@Result(name="success",type="xmlstr", params={"stringName", "result"})})
	public String handleVideoMsg() throws Exception {
		
		logger.info("msg type is WxRecvVideoMsg");
		
		WxRecvVideoMsg recvMsg = (WxRecvVideoMsg) this.request.getAttribute("recvMsg");
		WxSendMsg sendMsg = WeiXinTools.builderSendByRecv(recvMsg);
		this.result = WeiXinTools.getSendXmlStr(sendMsg);
		
		return SUCCESS;
	}
	
	@Action(value="handlegeomsg",
			results = {
				@Result(name="success",type="xmlstr", params={"stringName", "result"})})
	public String handleGeoMsg() throws Exception {
		
		logger.info("msg type is WxRecvGeoMsg");
		
		WxRecvGeoMsg recvMsg = (WxRecvGeoMsg) this.request.getAttribute("recvMsg");
		WxSendMsg sendMsg = WeiXinTools.builderSendByRecv(recvMsg);
		
		String openId = recvMsg.getFromUser();
		
		if (MongoUtil.findNearbyMMSession(openId) != null) {
			
			MongoUtil.removeNearbyMMSession(openId);
			
			UserLocation geo = new UserLocation();
			geo.setOpenId(openId);
			geo.setLatitude(recvMsg.getLatitude());
			geo.setLongitude(recvMsg.getLongitude());
			geo.setPrecision(-1);
			
			List<SnowMM> mmList = this.mmService.nearbyMM(geo);
			
			if (mmList == null || mmList.size() ==0) {
				sendMsg = new WxSendTextMsg(sendMsg, "雪花妹都不在线，请您稍后再试...");
				this.result = WeiXinTools.getSendXmlStr(sendMsg);
				return SUCCESS;
			}
			
			WxSendNewsMsg sendNewsMsg = new WxSendNewsMsg(sendMsg);
			DecimalFormat df1 = new DecimalFormat("0.00");
			
			for (int i=0; i<mmList.size(); i++) {
				
				if (i==0) {
					sendNewsMsg.addItem(mmList.get(i).getNickname()+" - "+mmList.get(i).getCurrLocation().getPoi()+"，距离"+df1.format(mmList.get(i).getDistance())+"KM", 
							mmList.get(i).getIntroduce(), 
							mmList.get(i).getPhotoUrlBig(),
							ConfigInfo.snowmmDetailUrl+"?mmid="+mmList.get(i).getMmid()+"&visitorId="+openId);
					continue;
				}
				
				sendNewsMsg.addItem(mmList.get(i).getNickname()+" - "+mmList.get(i).getCurrLocation().getPoi()+"，距离"+df1.format(mmList.get(i).getDistance())+"KM", 
						mmList.get(i).getIntroduce(), 
						mmList.get(i).getPhotoUrl(),
						ConfigInfo.snowmmDetailUrl+"?mmid="+mmList.get(i).getMmid()+"&visitorId="+openId);
				
				if (i==5) {
					break;
				}
			}
			
			sendNewsMsg.addItem("查看所有MM", "", "", ConfigInfo.snowmmListUrl+"?visitorId="+openId);
			
			this.result = WeiXinTools.getSendXmlStr(sendNewsMsg);
			return SUCCESS;
		}
		
		
		SnowMM mm = this.mmService.getMMbyOpenId(openId);
		
		if (mm != null) {
			// 用户是雪花妹，临时保存MM的位置
			SnowMMLocation loca = MongoUtil.findMMCheckinSession(mm.getMmid());
			if (loca != null) {
				MongoUtil.removeMMCheckinSession(mm.getMmid());
			}
			
			loca = new SnowMMLocation();
			loca.setMmid(mm.getMmid());
			loca.setLatitude(recvMsg.getLatitude());
			loca.setLongitude(recvMsg.getLongitude());
			loca.setLabel(recvMsg.getLabel());
			MongoUtil.saveMMCheckinSession(loca);
			
			StringBuffer buffer = new StringBuffer();  
		    buffer.append("欢迎回来，请回复 我在$位置$ ").append("\n\n");
		    buffer.append("例如：我在$简朴寨(沙湖店)$").append("\n");
		    buffer.append("请尽量填写商户的准确名称，以便客人知道您的确切位置");
			
			sendMsg = new WxSendTextMsg(sendMsg, buffer.toString());
			this.result = WeiXinTools.getSendXmlStr(sendMsg);
			return SUCCESS;
			
		}
		
		return SUCCESS;
	}
	
	@Action(value="handlelinkmsg",
			results = {
				@Result(name="success",type="xmlstr", params={"stringName", "result"})})
	public String handleLinkMsg() throws Exception {
		
		logger.info("msg type is WxRecvLinkMsg");
		
		WxRecvLinkMsg recvMsg = (WxRecvLinkMsg) this.request.getAttribute("recvMsg");
		WxSendMsg sendMsg = WeiXinTools.builderSendByRecv(recvMsg);
		this.result = WeiXinTools.getSendXmlStr(sendMsg);
		
		return SUCCESS;
	}
}
